import React, { Component, PropsWithChildren } from "react";

type IError = Error | null;

interface IProps {
  fallbackRender: (props: { error: IError }) => React.ReactElement;
}

interface IState {
  error: IError;
}

export default class ErrorBoundary extends Component<
  PropsWithChildren<IProps>,
  IState
> {
  state = { error: null };

  static getDerivedStateFromError(error: Error) {
    return { error };
  }

  render() {
    if (this.state.error) {
      return this.props?.fallbackRender({ error: this.state.error });
    }

    return this.props.children;
  }
}
